package com.zhkj.lib.base

import androidx.annotation.CallSuper
import androidx.lifecycle.ViewModelProvider
import com.zhkj.lib.http.HttpResponseStatus

abstract class ViewModelActivity<ViewModel : BaseViewModel> : BaseActivity() {

    lateinit var viewModel: ViewModel

    abstract fun setViewModel(): ViewModel

    @CallSuper
    override fun doBeforeInitUI() {
        viewModel = setViewModel()
        initViewModel()
    }

    /**
     * 页面销毁的时候，销毁ViewModel的数据
     */
    override fun onDestroy() {
        viewModel.onCleared()
        super.onDestroy()
    }

    /**
     * 初始化ViewModel
     */
    open fun initViewModel() {
    }

    /**
     * 生成ViewModel
     */
    inline fun <reified VM : BaseViewModel> createViewModel(): VM {
        val factory = ViewModelProvider.AndroidViewModelFactory(application)
        return ViewModelProvider(this, factory).get(VM::class.java)
    }

    /**
     * 处理不同数据状态时页面的显示(客户要求不显示加载框，故注释掉)
     */
    fun handlerResponseStatus(status: HttpResponseStatus.Status, errorTip: String, showLoading: Boolean = false) {
        when (status) {
            HttpResponseStatus.Status.START -> if (showLoading) showLoadingView()
            HttpResponseStatus.Status.SUCCESS -> if (showLoading) hideLoadingView()
            HttpResponseStatus.Status.FAILURE -> {
                if (showLoading) hideLoadingView()
                toast(errorTip)
            }
        }
    }
}